package cn.hxzy.icon.icon.service.impl;

import cn.hxzy.icon.icon.entity.Resource;
import cn.hxzy.icon.icon.entity.Role;
import cn.hxzy.icon.icon.repository.ResourceRepository;
import cn.hxzy.icon.icon.repository.RoleRepository;
import cn.hxzy.icon.icon.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author little black
 */
@Service("resourceService")
public class ResourceServiceImpl implements ResourceService {
    @Autowired
    private ResourceRepository resourceRepository;
    @Autowired
    RoleRepository roleRepository;

    /**
     * 查询全部
     *
     * @return
     */
    @Override
    public List<Resource> findAll() {
//        查询resource的父节点有些什么
        List<Resource> all = resourceRepository.findByPid(0);
//        查询到父节点有那些后，查询子节点有哪些
        for (Resource resource : all) {
            resource.setSon(resourceRepository.findByPid(resource.getId()));
        }
        return all;
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {
        resourceRepository.deleteById(id);
    }

    /**
     * 添加
     *
     * @param resource
     */
    @Override
    public void add(Resource resource) {
        resourceRepository.save(resource);
    }

    /**
     * ID查询
     * @param id
     * @return
     */
    @Override
    public Resource findById(Integer id) {
        Optional<Resource> byId = resourceRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }

    /**
     * 修改
     *
     * @param resource
     */
    @Override
    public void updeat(Resource resource) {
        resourceRepository.save(resource);
    }


    /**
     * 查询授权
     *
     * @param id
     * @return
     */
    @Override
    public List<Resource> findByRoleIdNotHave(Integer id) {
//        通过id找到role的对应信息
        Optional<Role> byId = roleRepository.findById(id);
//        判断信息是否存在
        if (byId.isPresent()) {
            Role role = byId.get();
            List<Resource> resourceList = role.getResourceList();
//            集合
            List<Integer> collect = resourceList.stream().map(Resource::getId).collect(Collectors.toList());
            if (collect.isEmpty()) {
                return resourceRepository.findAll();
            }
            return resourceRepository.findByIdNotIn(collect);
        }
        return null;
    }


}
